<?php
namespace App\Services;
use Firebase\JWT\BeforeValidException;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\SignatureInvalidException;
use function Hyperf\Config\config;

class JWTService {

    /**
     * 获取token
     * @param $data
     * @return mixed
     */
    public static function encode($data)
    {
        $time = time();
        $key = config('jwt.key');
        $issue = config('jwt.issue');
        $expire = config('jwt.expire');
        $payload = array(
            'iss' => $issue,
            'iat' => $time,
            'nbf' => $time,
            'exp' => $time + $expire,
            'data' => $data
        );
        return JWT::encode($payload, $key,'HS256');
    }

    /**
     * 解析token
     * @param $token
     * @return array|false
     */
    public static function decode($token)
    {
        $key = config('jwt.key');
        try {
            JWT::$leeway = 120;//当前时间减去60，把时间留点余地
            $decoded = JWT::decode($token, new Key($key,'HS256')); //HS256是默认方式，`在这里插入代码片`这里要和签发的时候对应
            $arr = (array)$decoded;
            return (array)$arr['data'];
        } catch (SignatureInvalidException $e) {  //签名不正确
            return false;
        } catch (BeforeValidException $e) {  // 签名在某个时间点之后才能用
            return false;
        } catch (ExpiredException $e) {  // token过期
            return false;
        }
    }
}